package com.itheima.springboottlias.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.springboottlias.common.utils.JwtUtils;
import com.itheima.springboottlias.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author iTaotao
 * @date 2023/7/18 19:58
 * @desciption: 登录拦截器
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        log.info("从请求头中获取令牌：{}",token);
        if(!StringUtils.hasText(token)){
            Result not_login = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(not_login);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;
        }

        try {
            JwtUtils.parseJWT(token);
            return true;
        } catch (Exception e) {
            log.info("令牌解析失败");
            Result not_login = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(not_login);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;

        }




    }
}
